<?php
namespace application\admin\panels;
use application\utilities\Utility;

class manage extends panel {
	public $name = 'Manage';
	
	public function title() {
		return 'Manage / ' . DB()->getVar("SELECT `ct_plural` FROM `cn_content_types` WHERE `ct_id`='".getQueryVar('type')."'");
	}
	
	public function handleData() {
		$contentType = getQueryVar('type');
		$contentTypePlural = DB()->getVar("SELECT `ct_plural` FROM `cn_content_types` WHERE `ct_id`='$contentType'");
		if($_REQUEST['perform_bulk_actions']) {
			$action = $_REQUEST['action'];
			/** Get array of all checked listings */
			$contents = $_REQUEST['content'];
			$contentImplode = "'".implode("', '", $contents)."'";
			switch($action) {
				case 'delete':
					DB()->query("DELETE FROM `cn_content` WHERE `content_id` IN ($contentImplode)");
					DB()->query("DELETE FROM `cn_content_type$contentType` WHERE `c{$contentType}_id` IN ($contentImplode)");
					Modulator()->runFunction('admin_delete_listings', array('contents'=>$contents, 'contentType'=>$contentType));
					$this->addMessage('success', $contentTypePlural.' deleted successfully.');
					break;
				case 'approve':
					DB()->query("UPDATE `cn_content` SET `content_status`='approved' WHERE `content_id` IN ($contentImplode)");
					foreach($contents as $content) {
						$email = DB()->getVar("SELECT `user_email` FROM `cn_users` RIGHT JOIN `cn_content` ON `content_author`=`user_id` WHERE `content_id`='$content'");
						
						if($email) {
							$contentType = strtolower(DB()->getVar("SELECT `ct_title` FROM `cn_content_types` INNER JOIN `cn_content` ON `content_type`=`ct_id` WHERE `content_id`='$content'"));
							mail($email, 'Your '.$contentType.' has been approved', 'You can access it at '.\application\system\Permalink::buildPermalink('content', $content), 'From: '.CN_SITE_NAME.' Admin <no-reply@torchdm.com>');
						}
					}
					$this->addMessage('success', 'Status set successfully.');
					break;
				case 'hide':
					DB()->query("UPDATE `cn_content` SET `content_status`='hidden' WHERE `content_id` IN ($contentImplode)");
					$this->addMessage('success', 'Status set successfully.');
					break;
				case 'pending':
					DB()->query("UPDATE `cn_content` SET `content_status`='pending' WHERE `content_id` IN ($contentImplode)");
					$this->addMessage('success', 'Status set successfully.');
					break;
					
			}
		}
		$this->display();
	}
	
	public function sidebar() {
		$contentType = $_REQUEST['type'];
		$contentTypePlural = DB()->getVar("SELECT `ct_plural` FROM `cn_content_types` WHERE `ct_id`='$contentType'");
		?>
			
			<form id="filter" class="inner" method="get">
				<input type="hidden" name="type" value="<?=getQueryVar('type')?>"/>
				<input type="hidden" name="display" value="<?=getQueryVar('display')?>"/>
				<ul id="filter-content">
				<li><label for="status">Status</label>
					<select name="status">
						<option <?=(getQueryVar('status') == 'approved') ? 'selected="selected"' : ''?> value="approved">Approved (<?=DB()->getCount("SELECT `content_id` FROM `cn_content` WHERE `content_type`='$contentType' AND `content_status`='approved'");?>)</option>
						<option <?=(getQueryVar('status') == 'pending') ? 'selected="selected"' : ''?> value="pending">Pending (<?=DB()->getCount("SELECT `content_id` FROM `cn_content` WHERE `content_type`='$contentType' AND `content_status`='pending'");?>)</option>
						<option <?=(getQueryVar('status') == 'hidden') ? 'selected="selected"' : ''?> value="hidden">Hidden (<?=DB()->getCount("SELECT `content_id` FROM `cn_content` WHERE `content_type`='$contentType' AND `content_status`='hidden'");?>)</option>
						<option <?=(getQueryVar('status') == 'stub') ? 'selected="selected"' : ''?> value="stub">Stub (<?=DB()->getCount("SELECT `content_id` FROM `cn_content` WHERE `content_type`='$contentType' AND `content_status`='stub'");?>)</option>
					</select>
				</li>
				<?php
					$allowedParents = unserialize(getOption('c'.$contentType.'_allowed_parents'));
					if(is_array($allowedParents)) :
					 $allowedParentsImplode = "'".implode("', '", $allowedParents)."'";
				?>
				<li><label for="child_of">Child Of</label>
					
					<?php if($grandchild = getQueryVar('grandchild_of')) $grandchildQuery = " AND `a`.`content_parent` = '$grandchild'";?>
				
					<select name="child_of">
						<option value="">All</option>
						
						<?php $results = DB()->getResults("SELECT DISTINCT `a`.`content_id`, `a`.`content_title` FROM `cn_content` `a` INNER JOIN `cn_content` `b` ON `a`.`content_id`=`b`.`content_parent` WHERE `a`.`content_type` IN ($allowedParentsImplode)$grandchildQuery ORDER BY `a`.`content_title`");?>
						<?php foreach($results as $result) : ?>
						<option <?=(getQueryVar('child_of') == $result->content_id) ? ' selected="selected"' : '';?> value="<?=$result->content_id?>"><?=$result->content_title?></option>
						<?php endforeach;?>
					</select>
				</li>
				<?php endif;?>
				<?php
				$allowedGrandparents = array();
				if(is_array($allowedParents)) {
					foreach($allowedParents as $parent) {
						$grandparents = unserialize(getOption('c'.$parent.'_allowed_parents'));
						if($grandparents) $allowedGrandparents = array_merge($allowedGrandparents, $grandparents);
					}
				}
				if(count($allowedGrandparents)) : $allowedGrandparents = "'".implode("', '", $allowedGrandparents)."'";?>
				<li><label for="grandchild_of">Grandchild Of</label>
				<select name="grandchild_of">
					<option value="">All</option>
					<?php $results = DB()->getResults("SELECT DISTINCT `a`.`content_id`, `a`.`content_title` FROM `cn_content` `a` INNER JOIN `cn_content` `b` ON `a`.`content_id`=`b`.`content_parent` WHERE `a`.`content_type` IN ($allowedGrandparents) ORDER BY `a`.`content_title`");?>
					<?php foreach($results as $result) : ?>
					<option <?=(getQueryVar('grandchild_of') == $result->content_id) ? ' selected="selected"' : '';?> value="<?=$result->content_id?>"><?=$result->content_title?></option>
					<?php endforeach;?>
				</select>
				</li>
				<?php endif;?>
				<li><label>Order by</label>
				<select name="order">
					<option <?=(getQueryVar('order') == 'title') ? ' selected="selected"' : '';?> value="title">Title</option>
					<option <?=(getQueryVar('order') == 'date') ? ' selected="selected"' : '';?> value="date">Date Created</option>
					<option <?=(getQueryVar('order') == 'parent') ? ' selected="selected"' : '';?> value="parent">Parent</option>
				</select>
				</li>
				<li>
					<label for="search">Search</label>
					<input type="text" name="search" value="<?=getQueryVar('search')?>"/>
				</li>
				<li>
					<h5>Show Fields</h5>
					<?php $fields = DB()->getResults("SELECT * FROM `cn_content_fields` WHERE `cf_content_type`='$contentType' ORDER BY `cf_display_name`");
					foreach($fields as $field) : ?>
					<label><input <?php if($field->cf_show) echo 'checked="checked"';?> type="checkbox" name="fields[]" value="<?=$field->cf_id?>"/> <?=$field->cf_display_name?></label>
					<?php endforeach;?>
				</li>
				<li>
					<input type="submit" value="Filter" id="filter-submit" name="filter_content" class="small-button"/>
				</li>
			</ul>
			</form>
			<form method="get" class="inner">
			
				<select id="action-to-take" name="bulk_actions">
					<option value="">Bulk Actions</option>
					<option value="delete">Delete Selected</option>
					<option value="approve">Approve</option>
					<option value="hide">Hide</option>
					<option value="pending">Make Pending</option>
				</select>
				<input type="submit" class="small-button" value="Go" id="perform-bulk-actions" name="perform_bulk_actions"/>
			</form>
			<script type="text/javascript">
			$('#filter').submit(function(e) {
				e.preventDefault();
				var values = $(this).serialize();
				$.ajax({
					url:concerto.admin.rootUrl + 'admin/?mode=ajax-content&' + values,
					beforeSend:function() {
						$('#main').fadeOut(200);
					},
					success:function(response) {
						//$('.torchd-ui-ajax-loader').remove();
						$('#main').html(response).fadeIn(100);
					}
				});

			});
			
			$('#perform-bulk-actions').click(function(e) {
				e.preventDefault();
				
				// Get all selected users
				var content = [];
				$('table.admin-table tbody').find('input[type="checkbox"]').each(function() {
					if($(this).attr('checked')) {
						content.push($(this).val());
					}
				});
				var action = $('#action-to-take').val();
				if(action) {
					if(action == 'delete') {
						torchd.ui.showDialog({
							type:'confirm',
							title:'Delete <?=$contentTypePlural?>?',
							message:'Are you sure you want to delete these <?=strtolower($contentTypePlural)?>?',
							onSubmit:function() {
								$.ajax({
									url:concerto.admin.rootUrl + 'admin?mode=handle-data&display=manage&type=<?=$contentType?>',
									type:'POST',
									data:{
										perform_bulk_actions:1,
										action:action,
										content:content
									},
									beforeSend:function() {
										torchd.ui.showDialog({
											title:'Performing actions...',
											type:'ajax-loader'
										});
									},
									success:function(response) {
										torchd.ui.closeAllDialogs();
										$('#main').html(response);
									}
								});
							}
						});
					}
					else {
						$.ajax({
							url:concerto.admin.rootUrl + 'admin?mode=handle-data&display=manage&type=<?=$contentType?>',
							type:'POST',
							data:{
								perform_bulk_actions:1,
								action:action,
								content:content
							},
							beforeSend:function() {
								torchd.ui.showDialog({
									title:'Performing actions...',
									type:'ajax-loader'
								});
							},
							success:function(response) {
								torchd.ui.closeAllDialogs();
								$.ajax({
									url:concerto.admin.rootUrl + 'admin/?mode=html-sidebar&display=manage',
									error:function(a,b,c) {
										alert(b);
									},
									success:function(sidebar) {
										
										$('#sidebar').html(sidebar);
					
										
									}
								});
								$('#main').html(response);
							}
						});
					
					}
				}
				
				
			});
			</script>
			<?php
	}
	
	public function display() {
		global $concerto;
		$contentType = $_REQUEST['type'];
		if(!getQueryVar('limit')) {
			setQueryVar('limit', 20);
		}
		
		if($_REQUEST['fields']) {
			// Check/uncheck shown fields
			DB()->query("UPDATE `cn_content_fields` SET `cf_show`='0' WHERE `cf_content_type`='$contentType'");
			DB()->query("UPDATE `cn_content_fields` SET `cf_show`='1' WHERE `cf_content_type`='$contentType' AND `cf_id` IN ('".implode("', '", $_REQUEST['fields'])."')");
		}
		$concerto->ContentQuery->initMainQuery();
		
		$shownColumns = DB()->getVarArray("SELECT `cf_display_name` FROM `cn_content_fields` WHERE `cf_content_type`='$contentType' AND `cf_show`='1'");
		
		?>
		<div class="box">
			
			<h3>Manage <b><?=DB()->getVar("SELECT `ct_plural` FROM `cn_content_types` WHERE `ct_id`='$contentType'")?></b></h3>
			
			<table class="admin-table" width="100%">
				<thead>
					<tr>
						<th class="first" width="2%"><input type="checkbox" class="select-all"/></th>
						
						<?php foreach($shownColumns as $column) : ?>
						<th><?=$column?></th>
						<?php endforeach;?>
						<th width="15%">Actions</th>
						<th class="last" width="2%"></th>
					</tr>
				</thead>
				<tfoot>
					<tr>
						<th class="first" width="2%"><input type="checkbox" class="select-all"/></th>
						<?php foreach($shownColumns as $column) : ?>
						<th><?=$column?></th>
						<?php endforeach;?>
						<th width="15%">Actions</th>
						<th class="last" width="2%"></th>
					</tr>
				</tfoot>
				<tbody>
					
					<?php $style = ''; 
					while(hasResults()) : initResult();?>
					<tr<?=$style?>>
						<td><input type="checkbox" name="contents[]" value="<?php displayField('ID');?>" class="selectee-all"/></td>				
						<?php foreach($shownColumns as $value) : ?>
						<td><?php displayField($value);?></td>
						<?php endforeach;?>
						<td><a target="view" href="<?php displayField('Permalink');?>">View</a> | <a target="edit" href="<?=CN_URL?>?form=edit_content&id=<?php displayField('ID');?>">Edit</a></td>
						<td></td>
					</tr>
					<?php $style = ($style == ' class="alternate"') ? '' : ' class="alternate"';?>
					<?php endwhile;?>
				</tbody>
			</table>
			<?php pageLinks(); ?>
		</div>
		<?php
	}
}
?>